package com.xuanmiao.smsback.web.controller.statement;

import com.panshi.hujin2.base.common.util.DozerUtils;
import com.panshi.hujin2.base.domain.page.Page;
import com.panshi.hujin2.base.domain.result.BasicResult;
import com.panshi.hujin2.base.domain.result.BasicResultCode;
import com.xuanmiao.smsback.dao.mapper.sms.MsgSendManageMapper;
import com.xuanmiao.smsback.service.platform.operator.UserInfoService;
import com.xuanmiao.smsback.service.statement.ConsumeStatementService;
import com.xuanmiao.smsback.service.statement.bo.ConsumeRankStatementBO;
import com.xuanmiao.smsback.service.statement.bo.ConsumeRecordStatementBO;
import com.xuanmiao.smsback.service.statement.bo.ConsumeTrendStatementBO;
import com.xuanmiao.smsback.service.statement.bo.SmsCountTrendDetailStatementBO;
import com.xuanmiao.smsback.service.statement.qo.BaseTimeQO;
import com.xuanmiao.smsback.service.statement.qo.ConsumeRecordStatementQO;
import com.xuanmiao.smsback.web.controller.statement.vo.*;
import com.xuanmiao.smsback.web.util.ExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.List;

/**
 * 消费报表数据
 */
@Api("消费报表数据")
@RestController
@RequestMapping("/statement/consume")
@Slf4j
public class ConsumeStatementController {

    @Autowired
    private ConsumeStatementService consumeStatementService;
    @Autowired
    private MsgSendManageMapper mgSendManageMapper;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    ExcelUtils excelUtils;

    @ApiOperation("消费排行")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "start" ,value = "时间开始" ,dataType = "Date",paramType = "query"),
            @ApiImplicitParam(name = "end" ,value = "时间结束" ,dataType = "Date",paramType = "query"),
    })
    @GetMapping("/rank")
    public BasicResult<List<ConsumeRankStatementVO>> rankdata(BaseTimeQO qo) {
        try {
            List<ConsumeRankStatementBO> resList = consumeStatementService.getRank(qo);
            if (CollectionUtils.isNotEmpty(resList)) {
                return BasicResult.ok(DozerUtils.convertList(resList, ConsumeRankStatementVO.class));
            }
            return BasicResult.ok(Collections.EMPTY_LIST);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return BasicResult.error(BasicResultCode.QUERY_FAIL.getCode(), BasicResultCode.QUERY_FAIL.getMessage());

        }
    }

    @ApiOperation("消费趋势")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "start" ,value = "时间开始" ,dataType = "Date",paramType = "query"),
            @ApiImplicitParam(name = "end" ,value = "时间结束" ,dataType = "Date",paramType = "query"),
    })
    @GetMapping("/trend")
    public BasicResult<ConsumeTrendStatementVO> trenddata(BaseTimeQO qo) {
        try {
            ConsumeTrendStatementBO res = consumeStatementService.getTrend(qo);

            ConsumeTrendStatementVO consumeTrendStatementVO = new ConsumeTrendStatementVO();
            consumeTrendStatementVO.setAmount(res.getAmount());
            consumeTrendStatementVO.setSmsCount(res.getSmsCount());
            consumeTrendStatementVO.setSmsFailedCount(res.getSmsFailedCount());
            consumeTrendStatementVO.setSmsSuccessCount(res.getSmsSuccessCount());
            if(org.apache.commons.collections4.CollectionUtils.isNotEmpty(res.getDetails())){
                consumeTrendStatementVO.setDetails(DozerUtils.convertList(res.getDetails(), ConsumeTrendDetailStatementVO.class));
            }else {
                consumeTrendStatementVO.setDetails(Collections.EMPTY_LIST);
            }

            if(org.apache.commons.collections4.CollectionUtils.isNotEmpty(res.getSmsFailedCountDetails())) {
                consumeTrendStatementVO.setSmsFailedCountDetails(DozerUtils.convertList(res.getSmsFailedCountDetails(), SmsCountTrendDetailStatementBO.class));
            }else {
                consumeTrendStatementVO.setSmsFailedCountDetails(Collections.EMPTY_LIST);
            }

            if(org.apache.commons.collections4.CollectionUtils.isNotEmpty(res.getSmsSuccessCountDetails())) {
                consumeTrendStatementVO.setSmsSuccessCountDetails(DozerUtils.convertList(res.getSmsSuccessCountDetails(), SmsCountTrendDetailStatementBO.class));
            }else {
                consumeTrendStatementVO.setSmsSuccessCountDetails(Collections.EMPTY_LIST);
            }

            if(org.apache.commons.collections4.CollectionUtils.isNotEmpty(res.getSmsCountDetails())) {
                consumeTrendStatementVO.setSmsCountDetails(DozerUtils.convertList(res.getSmsCountDetails(), SmsCountTrendDetailStatementBO.class));
            }else {
                consumeTrendStatementVO.setSmsCountDetails(Collections.EMPTY_LIST);
            }
            return BasicResult.ok(consumeTrendStatementVO);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return BasicResult.error(BasicResultCode.QUERY_FAIL.getCode(), BasicResultCode.QUERY_FAIL.getMessage());

        }
    }

    @ApiOperation("消费记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "createTimeStart" ,value = "时间开始" ,dataType = "Date",paramType = "query"),
            @ApiImplicitParam(name = "createTimeEnd" ,value = "时间结束" ,dataType = "Date",paramType = "query"),

            @ApiImplicitParam(name = "finishTimeStart" ,value = "时间开始" ,dataType = "Date",paramType = "query"),
            @ApiImplicitParam(name = "finishTimeEnd" ,value = "时间结束" ,dataType = "Date",paramType = "query"),

            @ApiImplicitParam(name = "consumerId" ,value = "用户商户ID" ,dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(name = "queueId" ,value = "队列ID" ,dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(name = "sendStatus" ,value = "状态" ,dataType = "Integer",paramType = "query"),
    })
    @GetMapping("/record")
    public BasicResult<List<ConsumeRecordStatementVO>> recorddata(ConsumeRecordStatementQO qo) {
        try {
            List<ConsumeRecordStatementBO> resList = consumeStatementService.getRecord(qo);
            if (CollectionUtils.isNotEmpty(resList)) {
                resList.stream().forEach(o->{
                    o.setConsumerCode(mgSendManageMapper.selectByPrimaryKey(o.getQueueId()).getConsumerCode());
                    o.setBusinessNo(userInfoService.getById(o.getUserId()).getBusinessNo());
                });
                return BasicResult.ok(DozerUtils.convertList(resList, ConsumeRecordStatementVO.class),qo.getPage());
            }
            return BasicResult.ok(Collections.EMPTY_LIST);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return BasicResult.error(BasicResultCode.QUERY_FAIL.getCode(), BasicResultCode.QUERY_FAIL.getMessage());

        }
    }

    @ApiOperation("消费记录导出")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "createTimeStart" ,value = "时间开始" ,dataType = "Date",paramType = "query"),
            @ApiImplicitParam(name = "createTimeEnd" ,value = "时间结束" ,dataType = "Date",paramType = "query"),

            @ApiImplicitParam(name = "finishTimeStart" ,value = "时间开始" ,dataType = "Date",paramType = "query"),
            @ApiImplicitParam(name = "finishTimeEnd" ,value = "时间结束" ,dataType = "Date",paramType = "query"),

            @ApiImplicitParam(name = "consumerId" ,value = "用户商户ID" ,dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(name = "queueId" ,value = "队列ID" ,dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(name = "sendStatus" ,value = "状态" ,dataType = "Integer",paramType = "query"),
    })
    @GetMapping("/record/export")
    public BasicResult<Void> exportRecordData(ConsumeRecordStatementQO qo, HttpServletResponse response) {
        try {
            Page page = new Page();page.setIsPaging(false);
            qo.setPage(page);
            List<ConsumeRecordStatementBO> resList = consumeStatementService.getRecord(qo);
            if (CollectionUtils.isNotEmpty(resList)) {
                //
                List<ConsumeRecordStatementExportBO> list = DozerUtils.convertList(resList, ConsumeRecordStatementExportBO.class);
                list.stream().forEach(o->{
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    if(o.getCreateTime()!=null){
                        o.setCreateTimeStr(sdf.format(o.getCreateTime()));
                    }
                    if(o.getSendTime()!=null){
                        o.setSendTimeStr(sdf.format(o.getSendTime()));
                    }
                    // 发送状态:1-发送中；2-等待；3-暂停；4-已取消；5-发送成功；6-暂停后失效；7-发送失败
                    Integer status = o.getStatus();
                    if(status != null){
                        if(status == 4){
                            o.setStatusStr("已取消");
                        }
                        if(status == 5){
                            o.setStatusStr("已完成");
                        }
                        if(status == 6){
                            o.setStatusStr("暂停失效");
                        }
                    }
                });
                excelUtils.exportExcel(response,list,"consumerecord");
            }
            return BasicResult.ok();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return BasicResult.error(BasicResultCode.QUERY_FAIL.getCode(), BasicResultCode.QUERY_FAIL.getMessage());

        }
    }
}